// utils/requestCancel.js
import axios from 'axios'

class RequestCancel {
  constructor() {
    this.pendingMap = new Map()
  }

  /**
   * 生成每个请求唯一的键
   * @param {*} config 
   * @returns 
   */
  getPendingKey(config) {
    const { url, method, params, data } = config
    return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')
  }

  /**
   * 添加请求
   * @param {*} config 
   */
  addPending(config) {
    const pendingKey = this.getPendingKey(config)
    config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => {
      if (!this.pendingMap.has(pendingKey)) {
        this.pendingMap.set(pendingKey, cancel)
      }
    })
  }

  /**
   * 移除请求
   * @param {*} config 
   */
  removePending(config) {
    const pendingKey = this.getPendingKey(config)
    if (this.pendingMap.has(pendingKey)) {
      const cancel = this.pendingMap.get(pendingKey)
      cancel(pendingKey)
      this.pendingMap.delete(pendingKey)
    }
  }

  /**
   * 取消所有pending状态的请求
   */
  cancelAllPending() {
    this.pendingMap.forEach(cancel => {
      cancel()
    })
    this.pendingMap.clear()
  }

  /**
   * 重置pendingMap
   */
  reset() {
    this.pendingMap = new Map()
  }
}

const requestCancel = new RequestCancel()

export default requestCancel